/*
 * 文件名：AuthRequestFilter.java
 * 版权：Copyright 2006-2011 AsiaInfo Tech. Co. Ltd. All Rights Reserved. 
 * 描述： AuthRequestFilter.java
 * 修改人：齐鹏飞
 * 修改时间：2011-9-5
 * 修改内容：新增
 */
package com.fengxing.ams.web.common;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.fengxing.ams.pub.constants.SystemParam;
import com.fengxing.ams.pub.manager.intf.IConfigManager;
import com.fengxing.ams.pub.util.AESUtil;
import com.fengxing.ams.pub.util.StringUtil;
import com.fengxing.ams.web.facade.mouble.user.UserVO;

/**
 * BPS鉴权filter，完成IP地址鉴权，Token鉴权
 * <p>
 * BPS鉴权filter，完成IP地址鉴权，Token鉴权
 * <p>
 * 
 * <pre>
 * </pre>
 * 
 * @author 齐鹏飞
 * @version CTMS V100R001 2011-9-5
 * @since CTMS V100R001C01
 */
@Component
public class AuthRequestFilter extends OncePerRequestFilter {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory
			.getLog(AuthRequestFilter.class);

	/**
	 * 上下文Manager
	 */
	private IContextManager contextManager;

	/**
	 * 系统配置
	 */
	private IConfigManager configManager;

	@Resource
	public void setConfigManager(IConfigManager configManager) {
		this.configManager = configManager;
	}

	/**
	 * 设置contextManager
	 * 
	 * @param contextManager
	 *            要设置的contextManager
	 */
	@Resource
	public void setContextManager(IContextManager contextManager) {
		this.contextManager = contextManager;
	}
	
	private static final Set<String> NONEED_AUTO = new HashSet<String> ();
	static {
		NONEED_AUTO.add("/user/login.do");
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest req,
			HttpServletResponse res, FilterChain filter)
			throws ServletException, IOException {
		
		try {
			String requestURI = req.getRequestURI();
			//获取token字段
			String tokenParam = req.getParameter("token");
			if (NONEED_AUTO.contains(requestURI) && StringUtil.isNull(tokenParam)) {
				filter.doFilter(req, res);
				return;
			}
			
			// Token鉴权
			if (StringUtil.isNull(tokenParam)) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}

			String token = new String(Base64.decodeBase64(tokenParam.getBytes("UTF-8")),
					"UTF-8");

			if (token.indexOf("|") < 0) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}

			String userID = token.split("\\|")[0];

			String aesBase = token.split("\\|")[1];

			byte[] aseBytes = Base64.decodeBase64(aesBase.getBytes("UTF-8"));

			byte[] ase;

			try {
				ase = AESUtil.aesDecode(
						this.configManager.getProperty(SystemParam.AUTH_KEY, ""),
						aseBytes);

			} catch (Exception e) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}

			String aseStr = new String(ase, "UTF-8");

			String[] authInfo = aseStr.split("\\|");

			if (authInfo.length != 5) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}

			String uid = authInfo[0];

			if (!uid.equals(userID)) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}

			String random = authInfo[4];

			if (random.length() != 8) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}
			//token鉴权通过，通过token获取userVO
			UserVO userVO = this.contextManager.getSession(tokenParam);
			if (userVO == null && !NONEED_AUTO.contains(requestURI)) {
				res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "   ");
				return;
			}
			this.contextManager.setUserVO(userVO);
			this.contextManager.setSessionEntity(tokenParam);
			
			filter.doFilter(req, res);
		} finally {
			this.contextManager.desctory();
		}
		
	}

}
